package com.atguigu.day09;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.DataTypes;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.TableResult;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.descriptors.Csv;
import org.apache.flink.table.descriptors.Kafka;
import org.apache.flink.table.descriptors.Schema;
import org.apache.kafka.clients.consumer.ConsumerConfig;

public class Flink10_SQL_Demo {
    public static void main(String[] args) throws Exception {
        //1.获取流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);


        SingleOutputStreamOperator<WaterSensor> waterSensorStream = env.socketTextStream("localhost", 9999)
                .map(new MapFunction<String, WaterSensor>() {
                    @Override
                    public WaterSensor map(String value) throws Exception {
                        String[] split = value.split(",");
                        return new WaterSensor(split[0], Long.parseLong(split[1]), Integer.parseInt(split[2]));
                    }
                });


        //2.获取表的执行环境
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        //将流转为表(未注册的表)
//        Table table = tableEnv.fromDataStream(waterSensorStream);

        //注册表
        //对Table对象进行注册
//        tableEnv.createTemporaryView("sensor", table);
        //直接对流进行注册
        tableEnv.createTemporaryView("sensor", waterSensorStream);

        //TODO 3.查询未注册的表
//        Table resultTable = tableEnv.sqlQuery("select * from " + table + " where id = 'sensor_1'");
//        TableResult execute = resultTable.execute();
//        execute.print();

//        tableEnv.executeSql("select * from "+table).print();
        tableEnv.executeSql("select id,sum(vc) from sensor group by id").print();

    }
}
